package com.zmn.plat.admin.controller.servcategory;

import java.util.*;
import java.util.stream.Collectors;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto.VtDTO;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.plat.common.constant.ProductConsts;
import com.zmn.plat.model.entity.category.BaseCategory;
import com.zmn.plat.model.entity.servcategory.*;
import com.zmn.plat.model.vo.servcategory.ServAssCategoryVO;
import com.zmn.plat.model.vo.servcategory.ServCategoryVO;

/**
 * 前台服务分类、产品分类关联功能
 *
 * @author linfeng
 * @version v1.0
 * @since 2019/09/23 9:15
 */
@Controller
@RequestMapping("/serv/showCateg/ass/")
public class ShowServAssCategoryListController extends ServCategoryBaseController {
    private Logger logger = LoggerFactory.getLogger(ShowServAssCategoryListController.class);

    @RequestMapping(value = "list")
    public ModelAndView list(@ModelAttribute ServAssCategoryQuery query) {
        query.setShowType(ProductConsts.EC_PRODUCT_TYPE);
        List<ServAssCategoryVO> items = servAssCategoryService.listPageByQuery(query);

        ModelAndView mav = new ModelAndView("servasscategory/show/list");

        List<VtDTO> categTwos = Collections.emptyList();
        List<BaseCategory> categOnes = baseCategoryService.listByParentIdForShow(GlobalConsts.TOP_ID, GlobalConsts.YES);
        List<ServCategory> servCategs = servCategoryService.listByQuery(new ServCategory());
        Integer servCategId = query.getServCategId();
        if (query.getServCategId() != null) {
            servCategId = query.getServCategId().intValue() == 0 ? null : query.getServCategId();
        }
        List<ShowCategoryAssociationVO> showCategoryAssociationList =
            showCategoryAssociationService.listByShowCategoryId(servCategId, query.getCategOneId(), query.getCategId());
        Map<String, List<ShowCategoryAssociationVO>> map =
            showCategoryAssociationList.stream().collect(Collectors.groupingBy(ShowCategoryAssociationVO::getRelateKey));

        if (NumberUtil.isPositiveInteger(query.getCategOneId())) {
            categTwos = baseCategoryService.listByParentId(query.getCategOneId());
        }

        mav.addObject("servCategs", servCategs);
        mav.addObject("categOnes", categOnes);
        mav.addObject("categTwos", categTwos);
        mav.addObject("vo", query);
        mav.addObject("items", items);
        mav.addObject("map", map);

        return mav;
    }

    @RequestMapping(value = "detail")
    @RequiresPermissions("/serv/showCateg/ass/detail.action")
    public ModelAndView detail(@RequestParam(value = "groupId", defaultValue = "0") Integer groupId) {
        ModelAndView mav = new ModelAndView("servasscategory/show/detail");

        ServAssCategory servAssCategory;
        if (groupId == 0 || groupId == null) {
            servAssCategory = new ServAssCategory();
        } else {
            servAssCategory = servAssCategoryService.findByKey(groupId);
        }

        mav.addObject("servAssCategory", servAssCategory);
        return mav;
    }

    @RequestMapping(value = "relateBackCategory")
    public ModelAndView list(@RequestParam(value = "groupId", defaultValue = "0") Integer groupId,
        @RequestParam(value = "servCategId", defaultValue = "0") Integer servCategId,
        @RequestParam(value = "categOneId", defaultValue = "0") Integer categOneId,
        @RequestParam(value = "categId", defaultValue = "0") Integer categId) {
        List<BaseCategory> categOnes = baseCategoryService.listByParentId(GlobalConsts.TOP_ID, GlobalConsts.YES);
        // 后台服务分类下的所有产品分类
        List<ServCategoryVO> servAssCategoryByServId =
            servAssCategoryService.findServAssCategoryByServIdAndShowType(servCategId, ProductConsts.ERP_PRODUCT_TYPE);

        // 已经关联的数据
        ShowCategoryAssociationQuery showCategoryAssociationQuery = new ShowCategoryAssociationQuery();
        showCategoryAssociationQuery.setShowServCategId(servCategId);
        showCategoryAssociationQuery.setShowCategOneId(categOneId);
        showCategoryAssociationQuery.setShowCategId(categId);
        List<ShowCategoryAssociation> showCategoryAssociationList =
            showCategoryAssociationService.listByQuery(showCategoryAssociationQuery);
        // 服务分类下已经被关联的分类
        List<ShowCategoryAssociationVO> list = showCategoryAssociationService.listByShowCategoryId(servCategId,null,null);
        //servAssCategoryByServId 必须是已配置的或者没有被其他关联的数据
        Map<String,ShowCategoryAssociation> showCategoryAssociationMap = showCategoryAssociationList.stream().collect(Collectors.toMap(o -> o.getCategOneId()+"_"+o.getCategId(), o -> o));
        Map<String,ShowCategoryAssociationVO> showCategoryAssociationVOMap =list.stream().collect(Collectors.toMap(o -> o.getCategOneId()+"_"+o.getCategId(), o -> o,(v1, v2) -> v1));

        List<ServCategoryVO> canShowList = new ArrayList<>();
        for (ServCategoryVO vo:servAssCategoryByServId){
            String key = vo.getCategOneId()+"_"+vo.getCategId();
            boolean canShow = Objects.nonNull(showCategoryAssociationMap.get(key)) || Objects.isNull(showCategoryAssociationVOMap.get(key));
            if(canShow){
                canShowList.add(vo);
            }
        }

        ServCategory servCategory = servCategoryService.findByKey(servCategId);
        if (servCategory == null) {
            servCategory = new ServCategory();
        }
        Map<Integer, List<ServCategoryVO>> map =
                canShowList.stream().collect(Collectors.groupingBy(ServCategoryVO::getCategOneId));

        for (Map.Entry<Integer, List<ServCategoryVO>> entry : map.entrySet()) {
            for (ServCategoryVO servCategoryVo : entry.getValue()) {
                for (ShowCategoryAssociation showCategoryAssociation : showCategoryAssociationList) {
                    if (showCategoryAssociation.getCategOneId().equals(servCategoryVo.getCategOneId())
                        && showCategoryAssociation.getCategId().equals(servCategoryVo.getCategId())) {
                        servCategoryVo.setRelated(true);
                        break;
                    } else {
                        servCategoryVo.setRelated(false);
                    }
                }
            }
        }

        ModelAndView mav = new ModelAndView("servasscategory/show/relatebackcategory");

        mav.addObject("groupId", groupId);
        mav.addObject("servCategId", servCategId);
        mav.addObject("categOneId", categOneId);
        mav.addObject("categId", categId);
        mav.addObject("servCategory", servCategory);
        mav.addObject("items", canShowList);
        mav.addObject("categOnes", categOnes);
        mav.addObject("map", map);
        return mav;
    }

}
